package com.dao;

import com.utils.JdbcUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

public class CourseDao {
    
    public List<Map<String, Object>> getAllCourses() throws SQLException {
        String sql = "SELECT * FROM Course ORDER BY courseno";
        List<Map<String, Object>> courses = new ArrayList<>();
        
        try (Connection conn = JdbcUtils.getDs().getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                Map<String, Object> course = new HashMap<>();
                course.put("courseNo", rs.getInt("courseno"));
                course.put("name", rs.getString("coursename"));
                course.put("credit", rs.getInt("coursecredit"));
                courses.add(course);
            }
        }
        return courses;
    }
    
    public void addCourse(Map<String, Object> course) throws SQLException {
        String sql = "INSERT INTO Course (courseno, coursename, coursecredit) VALUES (?, ?, ?)";
        
        try (Connection conn = JdbcUtils.getDs().getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, (Integer) course.get("courseNo"));
            pstmt.setString(2, (String) course.get("name"));
            pstmt.setInt(3, (Integer) course.get("credit"));
            
            pstmt.executeUpdate();
        }
    }
    
    public void updateCourse(Map<String, Object> course) throws SQLException {
        String sql = "UPDATE Course SET coursename = ?, coursecredit = ? WHERE courseno = ?";
        
        try (Connection conn = JdbcUtils.getDs().getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, (String) course.get("name"));
            pstmt.setInt(2, (Integer) course.get("credit"));
            pstmt.setInt(3, (Integer) course.get("courseNo"));
            
            pstmt.executeUpdate();
        }
    }
    
    public void deleteCourse(int courseNo) throws SQLException {
        String sql = "DELETE FROM Course WHERE courseno = ?";
        
        try (Connection conn = JdbcUtils.getDs().getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, courseNo);
            pstmt.executeUpdate();
        }
    }
} 